import { createSlice } from "@reduxjs/toolkit";


const musicSlice = createSlice({
  name: "music",
  initialState: {
    currentIndex: 0,
    playList: [
      ["001Bbywq2gicae"],
      ["002qI4qz4XTBUY"],
      ["001UiydT2NNPir"],
      ["0018zi4C0TaT8Q"],
      ["000naaAc1j3WJX"],
      ["00160kqX0vLpjO"],
      ["003elgGQ3c1uQN"],
      ["003MGIgX3Cr9Hj"],
      ["003uKKf71WF3v1"],
      ["002zQHGy0ao8TC"],
      ["0016IvEW0kcA1M"],
      ["003Ngvnw2Ks69Z"],
      ["004O1DHG4MjYOi"],
      ["002h62C40NbkWI"],
      ["001ufyHx10iWpg"],
      ["000weCyk0dt2V6"],
      ["002qPxvP32UrZK"],
      ["004GK4aP4TGbbG"],
      ["000xmJOc0h2yjT"],
      ["0043RVfI1vIomU"],
      ["000XrUoG0CHe9X"],
      ["002XhHCy1JaOF0"],
      ["003F1P942q4lEs"],
      ["001lRZ0z3XBRIj"],
      ["004JaCzc1KhTrU"],
      ["001lrqyg0FcPKk"],
      ["003eKeNV0t8IVi"],
      ["002nrqyW0p5LDT"],
      ["0014ahiq40MFQ5"],
      ["002sLKJ01lgURF"],
      ["000akynZ2Rbro5"],
      ["003IGhQO0JdnuC"],
      ["000I42sc1Lrn0d"],
    ],
  },
  reducers: {
    incrementCurrentIndex(state) {
      state.currentIndex++;
      if (state.currentIndex >= state.playList.length) state.currentIndex = 0;
    },
    decrementCurrentIndex(state) {
      state.currentIndex--;
      if (state.currentIndex < 0)
        state.currentIndex = state.playList.length - 1;
    },
    changeCurrentIndex(state, { payload }) {
      state.currentIndex = payload;
    },
    removeSong(state, { payload }) {
      state.playList.splice(payload, 1);

      if (payload < state.currentIndex) {
        // 被删的是当前播放之前的歌，currentIndex 往前移
        state.currentIndex--;
      } else if (payload === state.currentIndex) {
        // 被删的是当前播放的歌
        if (state.currentIndex >= state.playList.length) {
          // 如果删掉的是最后一首，跳回第一个
          state.currentIndex = 0;
        }
        // 否则 currentIndex 保持不变，继续播当前 index 上的新歌
      }
    },
    addSong(state, { payload }) {
      state.playList.push([payload]);

      if (state.playList.length === 1) {
        // 如果这是第一首歌，设置 currentIndex = 0
        state.currentIndex = 0;
      }
    },
  },
});

export const { incrementCurrentIndex,decrementCurrentIndex,changeCurrentIndex,removeSong,addSong} = musicSlice.actions;

export default musicSlice.reducer;
